package gormdb

import (
	"fmt"
	"log"
	"os"
	"slgw_web/serial/util"
	"sync"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	models "openzbox.com/frame/echo/models/sl_gw01"
)

var (
	db   *gorm.DB
	once sync.Once
	// dbPath = "E:/kaifa/SQLiteStudio/db/SL-Sokit?_foreign_keys=1" // 数据库文件路径，请根据实际情况修改
	dbPath = "gw0x_sl_db/gw0x.db" // 数据库文件路径
)

func init() {
	fmt.Println("当前系统版本：", util.Version)
	fmt.Println("项目启动")
	fmt.Println("sql初始化")

	GetDB()
	InitTable()
}

// GetDB 返回数据库连接
func GetDB() *gorm.DB {
	once.Do(func() {
		if err := os.MkdirAll("gw0x_sl_db", 0755); err != nil {
			panic("创建文件夹失败:" + err.Error())
		}
		newLogger := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags),
			logger.Config{
				SlowThreshold:             2 * time.Second,
				Colorful:                  true,
				IgnoreRecordNotFoundError: false,
				// ParameterizedQueries:      true,
				LogLevel: logger.Warn,
			})
		d, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{
			DisableForeignKeyConstraintWhenMigrating: true,
			Logger:                                   newLogger,
		})
		if err != nil {
			// util.MyPanic("数据库连接错误")
			panic("数据库连接错误" + err.Error())
		}
		// d.Exec("PRAGMA journal_mode=WAL;")
		// d.Exec("PRAGMA foreign_keys = ON;")
		db = d

	})

	return db
}

// 初始化数据库表
func InitTable() {
	// 删除
	// db.Migrator().DropTable(&models.SysUpgrade{})
	//初始化表
	db.AutoMigrate(&models.User{}, &models.Serial{}, &models.DeviceInfo{}, &models.TPITV{}, &models.Serial_Slave{},
		&models.Serial_Slave_Detail{}, &models.DeviceInfo_Detail{}, &models.CollectData{}, &models.SysUpgrade{}, &models.EthSetting{}, &models.SystemInfo{},
		&models.CollectDataSession{}, &models.DeviceInfo_Concentrator{}, &models.DeviceInfo_Concentrator_User{})
	//初始化数据

	var collectDataSession []models.CollectDataSession
	db.Find(&collectDataSession)
	if len(collectDataSession) == 0 {
		db.Create(&models.CollectDataSession{
			CollectDataList: "0",
		})
	}

	//默认账号
	var user []models.User
	db.Find(&user)
	if len(user) == 0 {
		db.Create(&models.User{
			UserName: "admin",
			PassWord: "admin",
		})
	}
	//默认采集周期
	// var tpitv []models.TPITV
	// db.Find(&tpitv)
	// if len(tpitv) == 0 {
	// 	db.Create(&models.TPITV{
	// 		TPITV:      60,
	// 		Timeout:    1,
	// 		RetryCount: 1,
	// 	})
	// 	util.TPITV = 60
	// 	util.Timeout = 1
	// 	util.RetryCount = 1
	// } else {
	// 	util.TPITV = tpitv[0].TPITV
	// 	if tpitv[0].Timeout == 0 {
	// 		util.Timeout = 1
	// 	} else {
	// 		util.Timeout = tpitv[0].Timeout
	// 	}
	// 	if tpitv[0].RetryCount == 0 {
	// 		util.RetryCount = 1
	// 	} else {
	// 		util.RetryCount = tpitv[0].RetryCount
	// 	}
	// }
	//默认以太网配置
	var eth []models.EthSetting
	db.Find(&eth)
	if len(eth) == 0 {
		ethSettings := []models.EthSetting{{
			Name:    "eth0",
			Type:    0,
			MAC:     "08:00:27:00:01:00",
			IP:      "192.168.0.100",
			NetMask: "255.255.255.0",
			Gateway: "192.168.0.1",
			DNS:     "8.8.8.8",
		},
			{
				Name:    "eth1",
				Type:    0,
				MAC:     "08:00:27:00:02:00",
				IP:      "192.168.1.101",
				NetMask: "255.255.255.0",
				Gateway: "192.168.1.1",
				DNS:     "8.8.4.4",
			},
		}

		db.Create(&ethSettings)
	}
	//默认FTP远程升级
	var sysUpgrade []models.SysUpgrade
	db.Find(&sysUpgrade)
	if len(sysUpgrade) == 0 {
		db.Create(&models.SysUpgrade{
			FTPIP:   "124.71.66.248",
			FTPPORT: "21",
			FTPMOD:  "0",
			FTPUN:   "gw0x",
			FTPPW:   "123654",
			FTPFN:   "GoApp_SL",
		})
	}

	var systemInfo []models.SystemInfo
	db.Find(&systemInfo)
	if len(systemInfo) == 0 {
		db.Create(&models.SystemInfo{
			ComType:      2,
			ATType:       2,
			IsRereported: 0,
		})
		util.ComType = 2
		util.ATType = 2
		util.IsRereported = 0

	} else {
		util.ComType = systemInfo[0].ComType
		util.ATType = systemInfo[0].ATType
		util.IsRereported = systemInfo[0].IsRereported
		util.TaskSetTimeUrl = systemInfo[0].TaskSetTimeUrl
	}

	var deviceInfo_Concentrator []models.DeviceInfo_Concentrator
	db.Find(&deviceInfo_Concentrator)
	util.DeviceInfo_Concentrator = deviceInfo_Concentrator
	var deviceInfo_Concentrator_User []models.DeviceInfo_Concentrator_User
	db.Find(&deviceInfo_Concentrator_User)
	util.DeviceInfo_Concentrator_User = deviceInfo_Concentrator_User
}
